import React,{ useEffect, useState } from 'react'; 

const App = () => {
  const [username, setUsername] = useState('');
  const [passwd, setPasswd] = useState('');
  const [data,setData] = useState({});
  const [message, setMessage] = useState({});
  useEffect(()=>{
    if (JSON.stringify(data) != '{}') {
      fetch('http://39.96.84.223:4567/verify/adminlogin', {
      method: 'POST',
      body: JSON.stringify(data),  
      headers : { 
          'Content-Type': 'application/json'
      } 
    })
        .then(res=>res.json())
        .then(res=>{
            successfulLogin(res);
        })
        .catch(error => failedLogin())
    }
  },[data])
  const addItem = () => {
    setData ({
      username: username,
      passwd: passwd
    })
  }
  const successfulLogin = (res) => {
    setMessage ({
      loginState: '登录成功',
      university: '学校是' + res.userinfo.university
    })
  }
  const failedLogin = () => {
    setMessage ({
      loginState: '登录失败',
      university: ''
    })
  }
  return(
    <div>
      <input type="text" 
        onChange={(e)=>{setUsername(e.target.value)}} 
        placeholder='请输入账号' 
        style={{display:'block', margin:'15px 5px', width:'200px', height:'20px'}}/>
      <input type="password" 
        onChange={(e)=>{setPasswd(e.target.value)}} 
        placeholder='请输入密码'
        style={{display:'block', margin:'15px 5px', width:'200px', height:'20px'}} />
      <button onClick={addItem} style={{margin:'5px 5px'}}>登录</button>
      <h2>{message.loginState}</h2>
      <p>{message.university}</p>
    </div>
  )
}

export default App;
